package com.alvinlkk.basic.chapter21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AtomicityTest implements Runnable {
    
    private int i = 0;
    
    //虽然return i是原子性操作，但是缺少同步的话，其数值可以在处于不稳定的中间状态时被读取。而且没有加volatile不能保证可见性。
    private synchronized int getValue() {return i; };  
    
    private synchronized void evenIncrement() { i++; i++;}
    
    @Override
    public void run() {
        while (true) {
            evenIncrement();
        }
    }
    
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        AtomicityTest at = new AtomicityTest();
        exec.execute(at);
        while (true) {
            int val = at.getValue();
            if(val % 2 != 0) {
                System.out.println(val);
                System.exit(0);;
            }
        }
    }
}
